#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Convenience script to generate documentation with Sphinx."""

assert __name__ == '__main__'

import argparse
import os
import shutil
import subprocess
import sys

INFRA_ROOT = os.path.dirname(os.path.abspath(__file__))


def cmd_run():
  """Generate html files from rst files.
  """

  # Clean
  subprocess.check_call(os.path.join('bootstrap', 'remove_orphaned_pycs.py'),
                        cwd=INFRA_ROOT)

  # Add missing rst files
  path = os.path.join('ENV', 'bin', 'sphinx-apidoc')
  subprocess.check_call([path,
                         '-o', os.path.join('doc', 'source', 'reference'),
                         'infra/'], cwd=INFRA_ROOT)

  # Build html documentation for rst files
  path = os.path.join('ENV', 'bin', 'sphinx-build')
  os.chdir(INFRA_ROOT)
  subprocess.check_call([path, '-b', 'html',
                         os.path.join('doc', 'source'),
                         os.path.join('doc', 'html')])


def cmd_clean():
  """Remove all files generated by the 'generate' command."""
  paths = (os.path.join(INFRA_ROOT, 'doc', 'source', 'reference'),
           os.path.join(INFRA_ROOT, 'doc', 'html'))
  for path in paths:
    try:
      shutil.rmtree(path)
    except OSError:
      pass
    else:
      print 'Removing %s ...' % path


def main():
  # Squash any existing path, we only want packages from the virtualenv.
  os.environ['PYTHONPATH'] = INFRA_ROOT

  parser = argparse.ArgumentParser()
  subparsers = parser.add_subparsers(title='commands')
  subparsers.add_parser('run').set_defaults(func=cmd_run)
  subparsers.add_parser('clean').set_defaults(func=cmd_clean)

  if len(sys.argv) == 1:
    return(cmd_run())

  args = parser.parse_args()
  return args.func()


if __name__ == '__main__':
  sys.exit(main())
